//
//  TSMainViewController.swift
//  TSProfitProject
//
//  Created by TmmmS on 2019/10/29.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import MJRefresh

let OYMultipleTableSource1 = "OYMultipleTableSource1"
let OYMultipleTableSource2 = "OYMultipleTableSource2"

let countdownSecond = 60

class TSMainViewController: TSBaseViewController {

    private let tableHeaderViewH = STATUSBAR_HEIGHT + 194
    private var tableController : TSBaseTableViewController!
    private var dataSource = Array<TSMainPageModel>()
    private var bannderArray = Array<TSBannerModel>()
    private var headerView : TSMainHeaderView!
    
    private var detailVc : TSMainDetailViewController? = nil
    private var isExistRacingModel = false
    private var isExistYachTModel = false
    
    private lazy var sectionHeaderView : TSMainSectionHeaderView = {
        var header = TSMainSectionHeaderView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - CGFloat(T_NAVBARHEIGHT)))
        header.delegate = self
        return header
    }()

    @objc private func refreshDatas() {
        
        requestTicketDatas { (_) in
            
        }

    }
    
    deinit {
        self.navigationController?.delegate = nil
    }
}

extension TSMainViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y + scrollView.contentInset.top
        
        if self.dataSource.count == 2 {
            if offsetY < 0 {
    
                var rect = headerView.frame
                rect.origin.y = offsetY - tableHeaderViewH
                rect.size.height = tableHeaderViewH - offsetY
                headerView.frame = rect
    
                headerView.updateHeaderViewH(offsetY: abs(offsetY))
            }
        }

        let minAlphaOffset : CGFloat = 0;
        let maxAlphaOffset : CGFloat = 40;
        
        let alpha = (offsetY - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset);
        if (alpha >= 0.6) {
            if #available(iOS 13, *) {
                UIApplication.shared.statusBarStyle = .darkContent
            } else {
                UIApplication.shared.statusBarStyle = .default
            }
        } else if (alpha <= 0.2) {
            UIApplication.shared.statusBarStyle = .lightContent
        }
    }
}

extension TSMainViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = TSMainDetailViewController.init()
        let model = dataSource[indexPath.row]
        vc.model = model
        navigationController?.pushViewController(vc, animated: true)
        
        detailVc = vc
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        145
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        110
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return sectionHeaderView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 20))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        20
    }
}

extension TSMainViewController : UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSMainPageTableViewCell.self)) as? TSMainPageTableViewCell
        if cell == nil {
            cell = TSMainPageTableViewCell(style: .default, reuseIdentifier: NSStringFromClass(TSMainPageTableViewCell.self))
        }
        
        cell?.delegate = self
        
        cell?.setupCell(model: self.dataSource[indexPath.row])
        
        return cell!
    }
    
}

//MARK: - TSMainPageTableViewCellDelegate
extension TSMainViewController : TSMainPageTableViewCellDelegate {
    
    func countdownEnd(model: TSMainPageModel) {
        
        NotificationCenter.default.post(name: TSCountDownFinishedNotification, object: nil)
        
        var existIndex = -1
        if self.dataSource.count > 0 {
            
            for index in 0..<self.dataSource.count {
                let pageModel = self.dataSource[index]
                if pageModel.identifier == model.identifier {
                    existIndex = index
                    break;
                }
            }
        }
        
        if existIndex >= 0 {
            self.dataSource[existIndex] = model
            UIView.performWithoutAnimation {
                tableController.tableView.reloadRows(at: [IndexPath.init(row: existIndex, section: 0)], with: .none)
            }
        }
                
        if model.identifier == OYMultipleTableSource1 {
            countdownStart1()
        } else {
            countdownStart2()
        }
    }
}

// MARK: - Network Request
extension TSMainViewController {
    
    func requestUserInfo() {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: true, success: { (data) in
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.getRequest()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    func getRequest(){
        
        let queue = DispatchQueue.init(label: "getCount")
        let group = DispatchGroup()
        
        queue.async(group: group, execute: {
            group.enter()
            
            self.requestNoticeDatas {
                group.leave()
            }
        })
        
        queue.async(group: group, execute: {
            group.enter()
            
            self.requestBannerDatas {
                group.leave()
            }
        })
        
        queue.async(group: group, execute: {
            group.enter()
            
            self.requestTicketDatas { (_) in
                group.leave()
            }
        })
        
//        queue.async(group: group, execute: {
//            group.enter()
//
//            self.requestRacingLottery { (success) in
//                group.leave()
//            }
//        })
//
//        queue.async(group: group, execute: {
//            group.enter()
//
//            self.requestYachtLottery { (success) in
//                group.leave()
//            }
//        })
        
        group.notify(queue: queue){
            DispatchQueue.main.async {
                
                CBToast.hiddenToastAction()

            }
        }
    }
    
    func requestNoticeDatas(completeCallback: @escaping() -> Void) {
        
        TSNetworkManager.request(TMSNetworkTools.getNotice, showHUD: false, success: { (data) in
        
            completeCallback()
            
            let array = data as? Array<Dictionary<String, Any>>
            var noticeArray : Array<TSAnnouncementModel> = []
            for item in array ?? Array() {
                let model = TSAnnouncementModel.deserialize(from: item)
                if let noticeModel = model {
                    noticeArray.append(noticeModel)
                }
            }
            self.sectionHeaderView.setupNoticeView(array: noticeArray)
            
        }) { (error) in
            
            completeCallback()
        }
    }
    
    func requestBannerDatas(_ completeCallback: @escaping() -> Void) {
        TSNetworkManager.request(TMSNetworkTools.getBanner, showHUD: false, success: { (data) in
            
            completeCallback()
            
            let array = data as? Array<Dictionary<String, Any>>
            for item in array ?? Array() {
                let model = TSBannerModel.deserialize(from: item)
                if let bannerModel = model {
                    self.bannderArray.append(bannerModel)
                }
            }
            self.headerView.setupHeaderView(array: self.bannderArray)
            
        }) { (error) in
            
            completeCallback()
        }
    }
    
    func requestTicketDatas(completeCallback: @escaping(_ success:Bool) -> Void) {
        
        let queue = DispatchQueue.init(label: "getTicket")
        let group = DispatchGroup()
        
        
        if !self.isExistRacingModel {
            TSLog("首次请求未获取到北京赛车")
            queue.async(group: group, execute: {
                group.enter()
                
                self.requestRacingLottery { (success) in
                    group.leave()
                }
            })
        }
        
        if !self.isExistYachTModel {
            TSLog("首次请求未获取到幸运飞艇")
            queue.async(group: group, execute: {
                group.enter()
                
                self.requestYachtLottery { (success) in
                    group.leave()
                }
            })
        }
        
        group.notify(queue: queue){
            
            completeCallback(true)
            
            DispatchQueue.main.async {
                
                self.tableController.tableView.mj_header.endRefreshing()
                
                self.tableController.tableView.mj_header.isHidden = self.dataSource.count == 2
                OYCountDownManager.sharedManager.reloadAllSource()
                
                self.tableController.tableView.reloadData()

            }
            
        }
    }
    
    func requestRacingLottery(completeCallback: @escaping(_ success:Bool) -> Void) {
        
        TSNetworkManager.request(TMSNetworkTools.getRacingInfo, showHUD: false, success: { (data) in
            
            let responseDic = data as? NSDictionary
            let tempModel = TSMainPageModel.deserialize(from: responseDic)
            if var model = tempModel {
                
                let date = Date.stringConvertDate(string: model.currentTime, dateFormat: "yyyy-MM-dd HH:mm:ss")
                let timeInterval = Date.getTimeDifferentWith(date: date)
                
                if timeInterval < 0 {
                    model.interval = abs(timeInterval)
                } else {
                    model.interval = 0
                }
                
                model.title = "北京赛车"
                model.imageName = "main_cell_race"
                model.identifier = OYMultipleTableSource1
                
                var existIndex = -1
                if self.dataSource.count > 0 {
                    
                    for index in 0..<self.dataSource.count {
                        let pageModel = self.dataSource[index]
                        if pageModel.identifier == model.identifier {
                            existIndex = index
                            break;
                        }
                    }
                }
                
                if existIndex >= 0 {
                    self.dataSource[existIndex] = model
                } else {
                    self.dataSource.append(model)
                }
                OYCountDownManager.sharedManager.addSourceWithIdentifier(identifier: OYMultipleTableSource1)
                
                self.isExistRacingModel = true
            }
            
            completeCallback(true)
            
        }) { (error) in
            completeCallback(false)
        }
    }
    
    func requestYachtLottery(completeCallback: @escaping(_ success:Bool) -> Void) {
        
        TSNetworkManager.request(TMSNetworkTools.getYachtInfo, showHUD: false, success: { (data) in
            
            let responseDic = data as? NSDictionary
            let tempModel = TSMainPageModel.deserialize(from: responseDic)
            if var model = tempModel {
                
                let date = Date.stringConvertDate(string: model.currentTime, dateFormat: "yyyy-MM-dd HH:mm:ss")
                let timeInterval = Date.getTimeDifferentWith(date: date)
                
                if timeInterval < 0 {
                    model.interval = abs(timeInterval)
                } else {
                    model.interval = 0
                }
                
                model.title = "幸运飞艇"
                model.imageName = "main_cell_yacht"
                model.identifier = OYMultipleTableSource2
                
                var existIndex = -1
                if self.dataSource.count > 0 {
                    
                    for index in 0..<self.dataSource.count {
                        let pageModel = self.dataSource[index]
                        if pageModel.identifier == model.identifier {
                            existIndex = index
                            break;
                        }
                    }
                }
                
                if existIndex >= 0 {
                    self.dataSource[existIndex] = model
                } else {
                    self.dataSource.append(model)
                }
                OYCountDownManager.sharedManager.addSourceWithIdentifier(identifier: OYMultipleTableSource2)
                
                self.isExistYachTModel = true
            }
            
            completeCallback(true)
            
        }) { (error) in
            completeCallback(false)
        }
    }
}

// MARK: - TSMainSectionHeaderViewDelegate
extension TSMainViewController : TSMainSectionHeaderViewDelegate {
    
    func didClickHeaderEntry(title: String) {
        
        switch title {
        case "充值":
            navigationController?.pushViewController(TSRechargeViewController(), animated: true)
        case "提现":
            navigationController?.pushViewController(TSWithDrawViewController(), animated: true)
        case "额度转换":
            navigationController?.pushViewController(TSLimitConvertViewController(), animated: true)
        case "钱包":
            let vc = TSWalletViewController()
            navigationController?.pushViewController(vc, animated: true)

        default:
            break
        }
    }
    
}

// MARK: - Private
extension TSMainViewController {
    
    func countdownStart1() {
        
        TSLog("开启赛车倒计时")
        
        var timeout = countdownSecond
        let queue = DispatchQueue.global()
        let timer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: queue)
        timer.schedule(deadline: .now(), repeating:  .milliseconds(1000))
        timer.setEventHandler {
            timeout = timeout - 1
            if timeout < 0 {
                DispatchQueue.main.async {
                    self.requestRacingLottery { (success) in
                        if success {
                            OYCountDownManager.sharedManager.reloadSourceWithIdentifier(identifier: OYMultipleTableSource1)
                            self.tableController.tableView.reloadData()
                            
                            if self.detailVc != nil {

                                self.detailVc?.updateVc(model: self.getModel(identifier: OYMultipleTableSource2))
                            }
                        } else {
                            self.countdownStart1()
                        }
                    }
                }
                timer.cancel()
            }
        }
        if #available(iOS 10.0, *) {
            timer.activate()
        } else {
            timer.resume()
            // Fallback on earlier versions
        }
    }
    
    func countdownStart2() {
        
        TSLog("开启游艇倒计时")
        
        var timeout = countdownSecond
        let queue = DispatchQueue.global()
        let timer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: queue)
        timer.schedule(deadline: .now(), repeating:  .milliseconds(1000))
        timer.setEventHandler {
            timeout = timeout - 1
            if timeout < 0 {
                DispatchQueue.main.async {
                    
                    self.requestYachtLottery { (success) in
                        if success {
                            OYCountDownManager.sharedManager.reloadSourceWithIdentifier(identifier: OYMultipleTableSource2)
                            self.tableController.tableView.reloadData()
                            
                            if self.detailVc != nil {
                                
                                self.detailVc?.updateVc(model: self.getModel(identifier: OYMultipleTableSource2))
                            }
                        } else {
                            self.countdownStart2()
                        }
                    }
                }
                timer.cancel()
            }
        }
        if #available(iOS 10.0, *) {
            timer.activate()
        } else {
            timer.resume()
            // Fallback on earlier versions
        }
    }
    
    func getModel(identifier:String) -> TSMainPageModel? {
        
        for index in 0..<self.dataSource.count {
            let pageModel = self.dataSource[index]
            if pageModel.identifier == identifier {
                return pageModel
            }
        }
        return nil
    }
}

// MARK: - LifeCycle
extension TSMainViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationController?.delegate = self

        configViews()
        
        requestUserInfo()
        
        // 启动倒计时管理
        OYCountDownManager.sharedManager.start()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        scrollViewDidScroll(tableController.tableView)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = .default
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        detailVc = nil
    }
}

// MARK: - Initialize
extension TSMainViewController {
    
    func configViews() {
        
        UIApplication.shared.statusBarStyle = .lightContent
        
        tableController = TSBaseTableViewController.init(style: .grouped)
        tableController.shouldDisplayEmptyAlert = false
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.contentInset = UIEdgeInsets(top: tableHeaderViewH, left: 0, bottom: 10, right: 0)
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(T_TABBARHEIGHT)
        }
        
        headerView = TSMainHeaderView.init(frame: CGRect(x: 0, y: -tableHeaderViewH, width: SCREEN_WIDTH, height: tableHeaderViewH))
        
        tableController.tableView.addSubview(headerView)
        
        tableController.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refreshDatas))
        tableController.tableView.mj_header.ignoredScrollViewContentInsetTop = tableHeaderViewH
    }
}

extension TSMainViewController : UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

        let isShowHomePage = viewController.isKind(of: TSMainViewController.self)
        self.navigationController?.setNavigationBarHidden(isShowHomePage, animated: false)
    }
}
